import { DisputeKind, DisputeStatus, DisputeTransaction, Order, OrderItem, OrderService, Refund } from "@mallfoundry/order"
import { Button, Card, Col, Descriptions, Divider, Image, Row, Space, Statistic, Steps, Typography } from "antd"
import classNames from "classnames"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { Link, useParams } from "react-router-dom"
import Page from "../../components/page"
import { OrderRefundApproveModal, OrderRefundDisapproveModal } from "./order-dispute-modals"
import classes from "./order-refund-detail.module.scss"

const { Text, Paragraph } = Typography
const { Countdown } = Statistic

/**
 * 获得倒计时格式，根据倒计时剩余时间生成格式。
 */
function countdownFormat(deadline: number) {
  const format: string[] = []
  if (deadline > 86400000) {
    format.push("D天")
  }
  if (deadline > 3600000) {
    format.push("H时")
  }
  if (deadline > 60000) {
    format.push("m分")
  }
  format.push("s秒")
  return _.join(format, "")
}

function renderRefundKind(kind?: DisputeKind): string {
  if (kind === DisputeKind.OnlyRefund) {
    return "仅退款"
  } else if (kind === DisputeKind.ReturnRefund) {
    return "退货退款"
  }
  return "未知"
}

interface RefundStatusLabelProps {
  status?: DisputeStatus
}

function RefundStatusLabel(props: RefundStatusLabelProps) {
  const { status } = props
  return <>
    {DisputeStatus.Applying === status && "待处理"}
    {DisputeStatus.Reapplying === status && "待买家处理"}
    {DisputeStatus.Cancelled === status && "退款取消"}
    {DisputeStatus.Disapproved === status && "待买家处理"}
    {DisputeStatus.Pending === status && "退款中"}
    {DisputeStatus.Succeeded === status && "退款成功"}
    {DisputeStatus.Failed === status && "退款失败"}
  </>
}

const STORE_DISPUTE_STATUTES = [DisputeStatus.Disapproved, DisputeStatus.Pending, DisputeStatus.Succeeded, DisputeStatus.Failed]
const CUSTOMER_DISPUTE_STATUTES = [DisputeStatus.Applying, DisputeStatus.Reapplying, DisputeStatus.Cancelled]

function renderOrderDisputeTransaction(transaction: DisputeTransaction) {
  const { status } = transaction

  let roleType = ""
  if (_.includes(STORE_DISPUTE_STATUTES, status)) {
    roleType = "商"
  } else if (_.includes(CUSTOMER_DISPUTE_STATUTES, status)) {
    roleType = "买"
  }
  let title: any = ""
  const descriptions: React.ReactNode[] = []
  if (status === DisputeStatus.Applying || status === DisputeStatus.Reapplying) {
    title = status === DisputeStatus.Applying ? <>
      <Text type="secondary">{roleType}家</Text>
      <Text> 发起了退款申请，等待商家处理</Text>
    </> : <>
      <Text type="secondary">{roleType}家</Text>
      <Text> 修改退款申请，等待商家处理</Text>
    </>
    descriptions.push(<Descriptions.Item key="售后方式" label="售后方式"
                                         children={<Text type="danger">{renderRefundKind(transaction.kind)}</Text>}/>)
    descriptions.push(<Descriptions.Item key="退款金额" label="退款金额" children={<Text type="danger" children={`￥${transaction.amount}`}/>}/>)
    descriptions.push(<Descriptions.Item key="退款原因" label="退款原因" children={transaction.reason}/>)
    descriptions.push(<Descriptions.Item key="退款说明" label="退款说明" children={_.isEmpty(transaction.notes) ? "无" : transaction.notes}/>)
  } else if (status === DisputeStatus.Disapproved) {
    title = <>
      <Text type="secondary">{roleType}家</Text>
      <Text> 拒绝了本次退款申请，等待买家修改</Text>
    </>
    descriptions.push(<Descriptions.Item key="拒绝原因" label="拒绝原因" children={transaction.disapprovalReason}/>)
  } else if (status === DisputeStatus.Pending) {
    title = <>
      <Text type="secondary">{roleType}家</Text>
      <Text> 同意退款给买家，正在退款中</Text>
    </>
    descriptions.push(<Descriptions.Item key="退款金额" label="退款金额" children={<Text type="danger" children={`￥${transaction.amount}`}/>}/>)
  } else if (status === DisputeStatus.Succeeded) {
    title = <>
      <Text type="secondary">{roleType}家</Text>
      <Text> 成功退款给买家，本次维权结束</Text>
    </>
    descriptions.push(<Descriptions.Item key="退款金额" label="退款金额" children={<Text type="danger" children={`￥${transaction.amount}`}/>}/>)
  }

  return <Steps.Step key={transaction.id}
                     className={classNames({
                       [classes.StoreRefundTransaction]: roleType === "商",
                     })}
                     icon={<>{roleType}</>}
                     description={
                       <Card title={title} size="small" bordered={false} extra={transaction.createdTime}
                             style={{ background: "#f7f8fa" }}>
                         <Descriptions size="small" column={1}>
                           {descriptions}
                         </Descriptions>
                       </Card>}/>
}

export default function OrderRefundDetail() {
  const [loading, setLoading] = useState(false)
  const { storeId, orderId, refundId } = useParams<{ storeId: string, orderId: string, refundId: string }>()
  const [order, setOrder] = useState(new Order())
  const [refund, setRefund] = useState(new Refund())
  const [transactions, setTransactions] = useState([] as DisputeTransaction[])
  const { status } = refund
  const [item, setItem] = useState(new OrderItem())

  const [disapproveModalVisible, setDisapproveModalVisible] = useState(false)
  const [approveModalVisible, setApproveModalVisible] = useState(false)

  useEffect(refreshOrder, [orderId])

  useEffect(() => {
    const { items, refunds } = order
    const findRefund = _.find(refunds, aRefund => aRefund.id === refundId)
    setRefund(_.isUndefined(findRefund) ? new Refund() : findRefund)
    if (findRefund) {
      setTransactions(_.reverse(findRefund.transactions))
      const { itemId } = findRefund
      const findItem = _.find(items, aItem => aItem.id === itemId)
      setItem(_.isUndefined(findItem) ? new OrderItem() : findItem)
    }
  }, [order, refundId])

  function refreshOrder() {
    setLoading(true)
    OrderService
      .getOrder(orderId)
      .then(setOrder)
      .finally(() => setLoading(false))
  }

  return (
    <div className={classes.OrderRefundDetail}>
      <Page.Header title="售后详情" ghost={false}/>
      <Page.Content loading={loading}>
        <Space direction="vertical" size="middle" style={{ width: "100%" }}>
          <Card>
            <Row gutter={[24, 24]}>
              <Col span={12}>
                <div className={classNames(classes.RefundStatus, {
                  [classes.RefundSucceededStatus]: status === DisputeStatus.Succeeded,
                  [classes.RefundFailedStatus]: status === DisputeStatus.Failed,
                })}>
                  <RefundStatusLabel status={status}/>
                </div>
                <span className={classes.RefundId}>售后编号：{refundId}</span>
              </Col>
              <Col span={12} className={classes.RefundApplicant}>
                <Text>申请人：{refund.applicant}</Text>
                <Divider type="vertical"/>
                <Text>申请时间：{refund.appliedTime}</Text>
              </Col>
            </Row>
            {
              (status === DisputeStatus.Applying || status === DisputeStatus.Reapplying) &&
              <div className={classes.RefundApplyingActions}>
                请在
                <Text type="warning" className={classes.ApplyingExpiredTime}>
                  <Countdown value={dayjs(refund.applyingExpiredTime).valueOf()}
                             format={countdownFormat(dayjs(refund.applyingExpiredTime).valueOf() - Date.now())}/>
                </Text>
                内处理，逾期未处理，将自动退款给买家
              </div>
            }
            {
              status === DisputeStatus.Disapproved &&
              <>
                <div className={classes.RefundDisapprovedActions}>
                  <Paragraph className={classes.MiniDescription}>买家修改申请后，商家需要重新处理</Paragraph>
                  买家需在
                  <Text type="warning" className={classes.ApplyingExpiredTime}>
                    <Countdown value={dayjs(refund.applyingExpiredTime).valueOf()}
                               format={countdownFormat(dayjs(refund.applyingExpiredTime).valueOf() - Date.now())}/>
                  </Text>
                  内处理，逾期未处理，退款申请将自动撤销
                </div>
              </>
            }
            {
              status === DisputeStatus.Succeeded &&
              <div className={classes.RefundSucceededActions}>
                <Typography.Text>退款金额：</Typography.Text>
                <Typography.Text type="danger" className={classes.RefundSucceededAmount}>￥{refund.amount}</Typography.Text>
              </div>
            }
            <Divider/>
            <Space direction="vertical" size={0}>
              <Typography.Text type="warning">系统提醒：</Typography.Text>
              <Typography.Text type="secondary">如果未发货，请点击同意退款给买家。</Typography.Text>
              <Typography.Text type="secondary">如果实际已发货，请主动与买家联系。</Typography.Text>
              <Typography.Text type="secondary">如果你逾期未处理，视作同意买家申请，系统将自动退款给买家。</Typography.Text>
            </Space>
          </Card>
          <Card className={classes.RefundDescriptions}>
            <Row>
              <Col span={6}>
                <Descriptions title="售后商品" size="small" column={1}>
                  <Descriptions.Item className={classes.RefundProductDescription}>
                    <Image src={refund.imageUrl} width={64}/>
                    <Paragraph ellipsis={{ rows: 3 }}>{refund.name}</Paragraph>
                  </Descriptions.Item>
                </Descriptions>
              </Col>
              <Col span={6}>
                <Descriptions title="售后信息" size="small" column={1}>
                  <Descriptions.Item label="售后方式" children={<Text type="danger">{renderRefundKind(refund.kind)}</Text>}/>
                  <Descriptions.Item label="退款金额" children={<Text type="danger">￥{refund.amount}</Text>}/>
                  <Descriptions.Item label="退款原因" children={refund.reason}/>
                  <Descriptions.Item label="退款说明" children={_.isEmpty(refund.notes) ? "无" : refund.notes}/>
                </Descriptions>
              </Col>
              <Col span={6}>
                <Descriptions title="购买信息" size="small" column={1}>
                  <Descriptions.Item label="商品单价">
                    <Text type="danger">￥{item.price}</Text>
                    <Text> x{item.quantity}件</Text>
                  </Descriptions.Item>
                  <Descriptions.Item label="实付金额">
                    <Text type="danger">￥{order.totalAmount}</Text>
                  </Descriptions.Item>
                  <Descriptions.Item label="发货件数">{item.quantity} 件</Descriptions.Item>
                  <Descriptions.Item label="发货状态">
                    {item.shipped ? "已发货" : "未发货"}
                    {/* {item.shipped && <Link to={`/stores/${storeId}/orders/${orderId}`}>{orderId}</Link>}*/}
                  </Descriptions.Item>
                  <Descriptions.Item label="订单编号">
                    <Link to={`/stores/${storeId}/orders/${orderId}`}>{orderId}</Link>
                  </Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>
          </Card>
          <Card title="协商记录" className={classes.RefundTransactions}>
            <Steps direction="vertical" size="small">
              {
                _.map(transactions, renderOrderDisputeTransaction)
              }
            </Steps>
          </Card>
          {
            (status === DisputeStatus.Applying
              || status === DisputeStatus.Reapplying) &&
            <Card>
              <OrderRefundApproveModal visible={approveModalVisible} dispute={refund}
                                       onCancel={() => setApproveModalVisible(false)}
                                       onOk={() => {
                                         setApproveModalVisible(false)
                                         refreshOrder()
                                       }}/>
              <OrderRefundDisapproveModal visible={disapproveModalVisible} dispute={refund}
                                          onCancel={() => setDisapproveModalVisible(false)}
                                          onOk={() => {
                                            setDisapproveModalVisible(false)
                                            refreshOrder()
                                          }}/>
              <Row gutter={16} justify="center">
                <Col>
                  <Button type="primary" htmlType="button"
                          onClick={() => setApproveModalVisible(true)}>同意{renderRefundKind(refund.kind)}</Button>
                </Col>
                <Col>
                  <Button onClick={() => setDisapproveModalVisible(true)}>拒绝{renderRefundKind(refund.kind)}</Button>
                </Col>
              </Row>
            </Card>
          }
        </Space>
      </Page.Content>
    </div>
  )
}
